﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Univar.Helpers;

namespace Univar
{
	public class CookieStore : CookieStore<string>
	{
		public CookieStore(string key) : base(key) { }
		public CookieStore(string key, Scopes scope) : base(key, scope) { }
		public CookieStore(string key, Scopes scope, TimeSpan lifeTime, bool isCompressed, bool isEncrypted)
			: base(key, scope, lifeTime, isCompressed, isEncrypted) { }
	}

	public class CookieStore<T> : StoreBase<T, CookieStore<T>>
	{
		public bool IsCompressed { get; set; }
		public bool IsEncrypted { get; set; }
		public TimeSpan LifeTime { get; set; }
		public string Path { get; set; }
		public string Domain { get; set; }
		public bool IsHttpOnly { get; set; }
		public bool IsSecureCookie { get; set; }

		public CookieStore(string key) : base(key) { }
		public CookieStore(string key, Scopes scope) : base(key, scope) { }
		public CookieStore(string key, Scopes scope, TimeSpan lifeTime, bool isCompressed, bool isEncrypted)
			: base(key, scope)
		{
			LifeTime = lifeTime;
			IsCompressed = isCompressed;
			IsEncrypted = isEncrypted;
		}

		protected override T GetValue(string key)
		{
			string value = Storage.Cookie.Get(key, IsCompressed, IsEncrypted, ThrowExceptionOnDeserializationOrDecryptionError);
			if (value == null)
				return DefaultValue;
			else
				return Serializer.Deserialize<T>(value, JsonEncoding.None, DefaultValue, ThrowExceptionOnDeserializationOrDecryptionError);
		}

		protected override void SetValue(string key, T value)
		{
			Storage.Cookie.Set<T>(key, value, LifeTime, IsCompressed, IsEncrypted,
				Path, Domain, IsHttpOnly, IsSecureCookie, ThrowExceptionOnDeserializationOrDecryptionError);
		}

		protected override object PlainValue
		{
			get { return Storage.Cookie.Get(Key); }
			set { Storage.Cookie.Set(Key, value); }
		}

		/// <summary>
		/// Returns the length of the serialized value.
		/// </summary>
		/// <returns></returns>
		public new long  GetSize() { return base.GetSize(); }
	}

}
